package com.apes.fn.scm.merchant.settlement.model;

import com.alibaba.fastjson.annotation.JSONField;
import com.apes.framework.jpa.DefaultPersistListener;
import com.apes.framework.jpa.Model;
import com.apes.framework.jpa.comment.Comment;
import com.apes.framework.jpa.generator.ApesGenerator;
import com.apes.framework.plugin.soe.annotations.State;
import com.apes.framework.plugin.soe.annotations.States;
import com.apes.framework.util.ApesConst;
import com.apes.framework.util.Arith;
import com.apes.framework.util.DateUtil;
import com.apes.scm.masterdata.party.model.PartyRole;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.SelectBeforeUpdate;

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @BelongsProject: apes-server
 * @BelongsPackage: com.apes.fn.scm.merchant.settlement
 * @ClassName: MerchantSettlement
 * @Author: pyb
 * @CreateTime: 2020-10-29 16:19
 * @Description: 赋能商户结算对账单
 * @Version: 1.0
 */
@Getter
@Setter
@SelectBeforeUpdate
@DynamicUpdate
@DynamicInsert
@Entity
@EntityListeners(DefaultPersistListener.class)
@Table(name = MerchantSettlement.CONST_TABLE_NAME)
public class MerchantSettlement extends Model {
    public static final String CONST_TABLE_NAME = "fn_merchant_settlement";

    @Id
    @Column(name = "id", length = 32)
    @ApesGenerator(code = CONST_TABLE_NAME, name = "赋能结算对账单编码", padding = 8, prefix = "%(merchant)")
    @Comment("编码")
    private String id;

    @NotNull
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "merchant_id", referencedColumnName = "id")
    @Comment("商户编码")
    private PartyRole merchant;

    @JSONField(format = DateUtil.SHOW_DATE_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "reconcile_begin_date")
    @Comment("开始对账日期")
    private Date reconcileBeginDate;

    @JSONField(format = DateUtil.SHOW_DATE_FORMAT)
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "reconcile_end_date")
    @Comment("结束对账日期")
    private Date reconcileEndDate;

    @Column(name = "inventory_money", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("常备库存金额")
    private double inventoryMoney = 0;

    @Column(name = "outstanding_money", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("挂账未清款")
    private double outstandingMoney = 0;

    @Column(name = "un_invoiced_money", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("未开发票金额")
    private double unInvoicedMoney = 0;

    @Column(name = "should_settle_business_money", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("应结算营业款")
    private double shouldSettleBusinessMoney = 0;

    @Column(name = "business_money", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("营业款(不含应收账款-外)")
    private double businessMoney = 0;

    @Column(name = "business_money_adjustment", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("营业款调整额")
    private double businessMoneyAdjustment = 0;

    @Column(name = "adjusted_turnover_money", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("调整后营业额")
    private double adjustedTurnoverMoney = 0;

    @Column(name = "platform_service_fee", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("平台服务费")
    private double platformServiceFee = 0;

    @Column(name = "platform_service_fee_reduced", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("平台服务费减免额")
    private double platformServiceFeeReduced = 0;

    @Column(name = "service_fee_adjustment", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("调整平台服务费")
    private double platformServiceFeeAdjustment = 0;

    @Column(name = "adjusted_service_fee", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("调整后平台服务费")
    private double adjustedPlatformServiceFee = 0;

    @Column(name = "accounts_receivable", nullable = false, columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("门店应收账款-平台外")
    private double accountsReceivable = 0;

    @Column(name = "accounts_receivable_back", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("门店应收账款回款-平台外")
    private double accountsReceivablePayBack = 0;


    @Column(name = "total_current_cost", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("本期成本费用合计")
    private double totalCurrentCost = 0;


    @Column(name = "total_expense_cost", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("本期费用合计")
    private double totalExpenseCost = 0;


    @Column(name = "total_businessDebit_cost", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("本期借支费用合计")
    private double totalBusinessDebitCost = 0;

    @Column(name = "cross_company_income", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("会员跨公司消费收入")
    private double crossCompanyIncome = 0;

    @Column(name = "cross_company_pay", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("会员跨公司消费支出")
    private double crossCompanyPay = 0;

    @Column(name = "un_deposited_amount", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("门店现金未存款")
    private double unDepositedAmount = 0;

    @Column(name = "loss_assessment_cost_fee", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("委托定损成本服务费")
    private double lossAssessmentCostFee = 0;

    @Column(name = "pre_settle_business_money", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("前期应结算金额")
    private double preSettleBusinessMoney = 0;

    @Column(name = "settle_business_money_total", columnDefinition = ApesConst.FIELD_MONEY_16_4_0)
    @Comment("总计应结算金额")
    private double settleBusinessMoneyTotal = 0;


    @Column(name = "note", length = 1000)
    @Comment("备注")
    private String note;


    @Column(name = "state", length = 36, nullable = false)
    @States(name = "订单状态", values = {
            @State(id = "sent", name = "新建"),
            @State(id = "squareAccounts", name = "清账"),
            @State(id = "reject", name = "驳回"),
            @State(id = "done", name = "已完成"),
            @State(id = "confirmation", name = "商户确认"),
            @State(id = "financialAudit", name = "财务审计"),
            @State(id = "serviceApprove", name = "客服审核"),
            @State(id = "payment", name = "已付款")})
    private String state;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "reconcile_uid", referencedColumnName = "id")
    @Comment("对账人")
    private PartyRole reconcileUid;

    @Column(name = "reconcile_date")
    @Comment("对账日期")
    private Date reconcileDate;


    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "service_approve_uid", referencedColumnName = "id")
    @Comment("客服审批人")
    private PartyRole serviceApproveUid;

    @Column(name = "service_approve_date")
    @Comment("客服审批日期")
    private Date serviceApproveDate;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "square_accounts_uid", referencedColumnName = "id")
    @Comment("清账人")
    private PartyRole squareAccountsUid;

    @Column(name = "square_accounts_date")
    @Comment("清账日期")
    private Date squareAccountsDate;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "merchant_confirmation_uid", referencedColumnName = "id")
    @Comment("商户确认人")
    private PartyRole merchantConfirmationUid;

    @Column(name = "merchant_confirmation_date")
    @Comment("商户确认日期")
    private Date merchantConfirmationDate;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "financial_audit_uid", referencedColumnName = "id")
    @Comment("财务审计人")
    private PartyRole financialAuditUid;

    @Column(name = "financial_audit_date")
    @Comment("财务审计日期")
    private Date financialAuditDate;

    @Column(name = "first_financial_audit_date")
    @Comment("财务首次审计日期")
    private Date firstFinancialAuditDate;

    @Column(name = "invoice_number", length = 256)
    @Comment("发票号码")
    private String invoiceNumber;

    @Column(name = "invoice_apply_id", length = 256)
    @Comment("发票申请单号")
    private String invoiceApplyId;

    @OneToMany(mappedBy = "merchantSettlement", cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH}, orphanRemoval = true)
    private List<CostSummary> costSummaries = new ArrayList<>();

    public List<CostSummary> getCostSummaries() {
        if (costSummaries == null) costSummaries = new ArrayList<>();
        for (CostSummary costSummary : costSummaries) {
            costSummary.setMerchantSettlement(this);
        }
        return costSummaries;

    }

    @OneToMany(mappedBy = "merchantSettlement", cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH}, orphanRemoval = true)
    private List<MerchantExpenseItem> merchantExpenseItems = new ArrayList<>();

    public List<MerchantExpenseItem> getMerchantExpenseItems() {
        if (merchantExpenseItems == null) merchantExpenseItems = new ArrayList<>();
        for (MerchantExpenseItem merchantExpenseItem : merchantExpenseItems) {
            merchantExpenseItem.setMerchantSettlement(this);
        }
        return merchantExpenseItems;

    }

    @OneToMany(mappedBy = "merchantSettlement", cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH}, orphanRemoval = true)
    private List<MerchantBusinessDebitItem> merchantBusinessDebitItems = new ArrayList<>();

    public List<MerchantBusinessDebitItem> getMerchantBusinessDebitItems() {
        if (merchantBusinessDebitItems == null) merchantBusinessDebitItems = new ArrayList<>();
        for (MerchantBusinessDebitItem merchantBusinessDebitItem : merchantBusinessDebitItems) {
            merchantBusinessDebitItem.setMerchantSettlement(this);
        }
        return merchantBusinessDebitItems;

    }

    @Transient
    private String candidates;

    public void computeAmt() {
        shouldSettleBusinessMoney = 0;
        totalExpenseCost = 0;
        totalCurrentCost = 0;
        totalBusinessDebitCost = 0;
        for (CostSummary costSummary : costSummaries) {
            totalCurrentCost += costSummary.getCurrentPeriodActualDeducted();
        }
        for (MerchantExpenseItem merchantExpenseItem : merchantExpenseItems) {
            totalExpenseCost += merchantExpenseItem.getCurrentAmount();
        }

        for (MerchantBusinessDebitItem merchantBusinessDebitItem : merchantBusinessDebitItems) {
            totalBusinessDebitCost += merchantBusinessDebitItem.getCurrentAmount();
        }

        shouldSettleBusinessMoney = Arith.round(adjustedTurnoverMoney - adjustedPlatformServiceFee + accountsReceivablePayBack - totalCurrentCost + crossCompanyIncome +crossCompanyPay -unDepositedAmount +platformServiceFeeReduced,2);
        settleBusinessMoneyTotal = shouldSettleBusinessMoney + preSettleBusinessMoney;
    }


}
